package software.lib.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by Wang on 2017/5/4.
 */
@WebFilter(filterName = "0DataTrackFilter",urlPatterns = "/*")
public class DataTrackFilter implements Filter {

    private final CommonsMultipartResolver multipartResolver;

    public DataTrackFilter() {
        multipartResolver = new CommonsMultipartResolver();
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

//      允许跨域
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST");


        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        //路径验证
        String url = request.getServletPath();

//        if(!StringUtils.startsWithAny(url, new String[]{"/plugins","/login","/user","/uploadFileTo","/isExist","/download","/charge/receipt","/driver/meeting/check","/driver/driverShowApplyCheckPrint"})
//                &&!url.trim().equals("/")){
//            if(request.getSession().getAttribute("user")==null){
//                response.setStatus(401);
//                response.setContentType("text/html;charset=utf-8");
//                PrintWriter out = response.getWriter();
//                out.print("您尚未登陆，请登录后访问！");
//                out.flush();
//                out.close();
//                return;
//            }
//        }

        //用于测试 监控用户请求
//        System.out.println("Track begin......");
        System.out.print(url);
        String method = request.getMethod();
        System.out.println("\t"+method);
        if(StringUtils.endsWithIgnoreCase("POST",method) && StringUtils.contains(request.getContentType(),"multipart/form-data")){
            MultipartHttpServletRequest multiReq = multipartResolver.resolveMultipart(request);
            request = multiReq;
        }
        Map<String,String[]> maps = request.getParameterMap();
        for(Map.Entry<String,String[]> entry:maps.entrySet()){
            System.out.println(entry.getKey()+"="+decodeStringArray(entry.getValue()));
        }
//        System.out.println("Track end......\n");

//      用于某些情况下的Spring调用
//      ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        long startTime=System.currentTimeMillis();
        chain.doFilter(request, response);
        long endTime=System.currentTimeMillis();
        System.out.println("Time Spend "+(endTime-startTime));
    }

    public void init(FilterConfig config) throws ServletException {
        String webRootPath =config.getServletContext().getRealPath("/");
        System.setProperty("webapps.root" , webRootPath+"/");
        String path = System.getProperty("webapps.root");
        System.out.println("webapps.root:"+path);
    }

    private String decodeStringArray(String[] ss){
        if(ss.length == 0)
            return "";
        if(ss.length == 1)
            return ss[0];
        String s = "";
        for(int i = 0;i < ss.length-1;++i){
            s += ss[i];
            s += " & ";
        }
        s+=ss[ss.length-1];
        return s;
    }



//    private static ApplicationContext ctx;
//
//    public static ApplicationContext getCtx() {
//        return ctx;
//    }

}
